<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>链接管理器</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .link-container {
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .add-link-form {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: flex-end;
        }
        .form-group {
            flex-grow: 1;
            min-width: 200px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        input[type="text"], input[type="url"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        .add-button {
            padding: 8px 15px;
            font-size: 16px;
        }
        .link-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .link-table th {
            background-color: #f2f2f2;
            padding: 10px;
            text-align: left;
            border-bottom: 2px solid #ddd;
        }
        .link-table td {
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .edit-button {
            background-color: #2196F3;
        }
        .edit-button:hover {
            background-color: #0b7dda;
        }
        .delete-button {
            background-color: #f44336;
        }
        .delete-button:hover {
            background-color: #d32f2f;
        }
        .save-button {
            background-color: #4CAF50;
        }
        .cancel-button {
            background-color: #9e9e9e;
        }
        .cancel-button:hover {
            background-color: #757575;
        }
        .hidden {
            display: none;
        }
        .link-row.editing td input {
            width: 100%;
            box-sizing: border-box;
        }
        .empty-message {
            text-align: center;
            padding: 20px;
            color: #757575;
        }
    </style>
</head>
<body>
    <h1>链接管理器</h1>
    
    <div class="link-container">
        <div class="add-link-form">
            <div class="form-group">
                <label for="link-url">链接地址</label>
                <input type="url" id="link-url" placeholder="请输入链接地址" required>
            </div>
            <div class="form-group">
                <label for="link-description">链接描述</label>
                <input type="text" id="link-description" placeholder="请输入链接描述" required>
            </div>
            <button class="add-button" onclick="addLink()">+ 添加链接</button>
        </div>
        
        <table class="link-table">
            <thead>
                <tr>
                    <th style="width: 40%">链接地址</th>
                    <th style="width: 40%">链接描述</th>
                    <th style="width: 20%">操作</th>
                </tr>
            </thead>
            <tbody id="links-container">
                <!-- 链接将通过JavaScript动态添加到这里 -->
            </tbody>
        </table>
        <div id="empty-message" class="empty-message">暂无链接，请点击"添加链接"按钮添加新链接</div>
    </div>

    <script>
        // 存储链接数据
        let links = [];
        
        // 页面加载时显示保存的链接
        document.addEventListener('DOMContentLoaded', function() {
            // 先从服务器加载链接
            loadLinksFromServer();
        });
        
        // 从服务器加载链接
        function loadLinksFromServer() {
            fetch('/text2html/links')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('从服务器获取链接失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.links && Array.isArray(data.links)) {
                        links = data.links;
                        displayLinks();
                        
                        // 同步到本地存储
                        localStorage.setItem('links', JSON.stringify(links));
                    } else {
                        // 如果服务器没有数据，尝试从本地存储加载
                        loadLinksFromLocalStorage();
                    }
                })
                .catch(error => {
                    console.error('从服务器加载链接错误:', error);
                    // 如果服务器请求失败，从本地存储加载
                    loadLinksFromLocalStorage();
                });
        }
        
        // 从本地存储加载链接
        function loadLinksFromLocalStorage() {
            const savedLinks = localStorage.getItem('links');
            if (savedLinks) {
                links = JSON.parse(savedLinks);
                displayLinks();
            }
        }
        
        // 显示链接
        function displayLinks() {
            const container = document.getElementById('links-container');
            const emptyMessage = document.getElementById('empty-message');
            
            // 清空容器
            container.innerHTML = '';
            
            if (links.length === 0) {
                emptyMessage.classList.remove('hidden');
            } else {
                emptyMessage.classList.add('hidden');
                
                // 添加所有链接
                links.forEach((link, index) => {
                    const row = document.createElement('tr');
                    row.className = 'link-row';
                    row.dataset.index = index;
                    
                    row.innerHTML = `
                        <td class="link-url"><a href="${link.url}" target="_blank">${link.url}</a></td>
                        <td class="link-description">${link.description}</td>
                        <td class="link-actions">
                            <div class="action-buttons">
                                <button class="edit-button" onclick="editLink(${index})">编辑</button>
                                <button class="delete-button" onclick="deleteLink(${index})">删除</button>
                            </div>
                        </td>
                    `;
                    
                    container.appendChild(row);
                });
            }
        }
        
        // 添加新链接
        function addLink() {
            const urlInput = document.getElementById('link-url');
            const descriptionInput = document.getElementById('link-description');
            
            const url = urlInput.value.trim();
            const description = descriptionInput.value.trim();
            
            if (!url || !description) {
                alert('请填写完整的链接信息');
                return;
            }
            
            // 创建新链接对象并添加到数组
            links.push({
                url: url,
                description: description
            });
            
            // 保存到本地存储和服务器
            saveLinks();
            
            // 更新显示
            displayLinks();
            
            // 清空输入框
            urlInput.value = '';
            descriptionInput.value = '';
            
            // 聚焦到URL输入框，方便继续添加
            urlInput.focus();
        }
        
        // 编辑链接
        function editLink(index) {
            const link = links[index];
            const row = document.querySelector(`.link-row[data-index="${index}"]`);
            
            // 将行转换为编辑模式
            row.classList.add('editing');
            row.innerHTML = `
                <td>
                    <input type="url" class="edit-url" value="${link.url}" required>
                </td>
                <td>
                    <input type="text" class="edit-description" value="${link.description}" required>
                </td>
                <td>
                    <div class="action-buttons">
                        <button class="save-button" onclick="saveEdit(${index})">保存</button>
                        <button class="cancel-button" onclick="cancelEdit()">取消</button>
                    </div>
                </td>
            `;
        }
        
        // 保存编辑
        function saveEdit(index) {
            const row = document.querySelector(`.link-row[data-index="${index}"]`);
            const urlInput = row.querySelector('.edit-url');
            const descriptionInput = row.querySelector('.edit-description');
            
            const url = urlInput.value.trim();
            const description = descriptionInput.value.trim();
            
            if (!url || !description) {
                alert('请填写完整的链接信息');
                return;
            }
            
            // 更新链接数据
            links[index] = {
                url: url,
                description: description
            };
            
            // 保存到本地存储和服务器
            saveLinks();
            
            // 更新显示
            displayLinks();
        }
        
        // 取消编辑
        function cancelEdit() {
            displayLinks();
        }
        
        // 删除链接
        function deleteLink(index) {
            if (confirm('确定要删除这个链接吗？')) {
                // 从数组中移除
                links.splice(index, 1);
                
                // 保存到本地存储和服务器
                saveLinks();
                
                // 更新显示
                displayLinks();
            }
        }
        
        // 保存链接到本地存储和服务器
        function saveLinks() {
            // 保存到本地存储
            localStorage.setItem('links', JSON.stringify(links));
            
            // 保存到服务器
            saveLinksToServer();
        }
        
        // 保存链接到服务器
        function saveLinksToServer() {
            fetch('/text2html/links', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ links: links })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存到服务器失败');
                }
                return response.json();
            })
            .then(data => {
                console.log('链接已保存到服务器', data);
            })
            .catch(error => {
                console.error('保存到服务器错误:', error);
                alert('链接已保存在本地，但保存到服务器失败，请检查网络连接');
            });
        }
    </script>
</body>
</html>
